package com.lv.service.utils

import android.content.Context
import android.content.Intent
import android.net.Uri
import android.view.View
import com.alibaba.android.arouter.facade.Postcard
import com.alibaba.android.arouter.facade.callback.NavigationCallback
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.SPStaticUtils
import com.google.gson.reflect.TypeToken
import com.luck.picture.lib.entity.LocalMedia
import com.lv.common.bean.CustomMessageChatBean
import com.lv.common.utils.ARoutUtils
import com.lv.common.utils.Constants
import com.lv.common.utils.TimeUtil
import com.lv.service.bean.AroutBean
import com.lv.service.bean.ViewTypeBean
import com.lv.service.bean.ViewTypeStringBean
import com.lv.service.net.ADClickReqBody
import com.lv.service.repo.UserInfo

/**
 * 作者： ygx
 * 创建日期：2023/2/11 2:49 PM
 * 签名： 天行健，君子以自强不息；地势坤，君子以厚德载物。
 * -    _              _           _     _   ____  _             _ _
 * -   / \   _ __   __| |_ __ ___ (_) __| | / ___|| |_ _   _  __| (_) ___
 * -  / _ \ | '_ \ / _` | '__/ _ \| |/ _` | \___ \| __| | | |/ _` | |/ _ \
 * - / ___ \| | | | (_| | | | (_) | | (_| |  ___) | |_| |_| | (_| | | (_) |
 * -/_/   \_\_| |_|\__,_|_|  \___/|_|\__,_| |____/ \__|\__,_|\__,_|_|\___/
 * <p>
 * You never know what you can do until you try !
 * ----------------------------------------------------------------
 * 描述：
 */
class YgxAroutPageKt {

    companion object {
        //先进首页再进目标路由
        fun aroutPager_home(mContext: Context, t: String, ti: String, tt: String) {
            ARouter.getInstance().build(ARoutUtils.HomeActivityURL)
                .withInt("tabId", 2)
                .navigation(
                    mContext,
                    object : NavigationCallback {
                        override fun onFound(postcard: Postcard?) {
                        }

                        override fun onLost(postcard: Postcard?) {
                        }

                        override fun onArrival(postcard: Postcard?) {
                            when (t) {


                                Constants.MESSAGE_TAG_1046, Constants.MESSAGE_TAG_121 -> {//列表1046 详情121

                                }


                                else -> {

                                }

                            }
                        }

                        override fun onInterrupt(postcard: Postcard?) {
                        }

                    })
        }

        fun aroutPager(
            mContext: Context,
            tag: String?,
        ) {
            when (tag) {//0无  1 商务合作  2商品  3店铺 4双跳 5本地工厂  6品牌工厂  7必找工厂  8批发好价  9品牌热卖  10 附近商品  11热销  12特惠活动 13新公司上线 14拨打电话 15开店 16找货啦 17订单详情  18完善信息

                "5" -> {//本地工厂
                    ARouter.getInstance().build(ARoutUtils.FactoryLocationTabActivity).navigation()
                }

                "6" -> {//品牌工厂
                    ARouter.getInstance().build(ARoutUtils.BrandFactoryTabActivity).navigation()
                }

                "7" -> {//必找工厂
                    ARouter.getInstance().build(ARoutUtils.FactoryMustTabActivity).navigation()
                }

                "8" -> {//批发专栏
                    ARouter.getInstance().build(ARoutUtils.WholeSalerActivity).navigation()
                }

                "12" -> {//特惠活动
                    ARouter.getInstance().build(ARoutUtils.CouponActionTabActivity).navigation()
                }

                "13" -> {//新店上线
                    ARouter.getInstance().build(ARoutUtils.NewCompanyOnLineActivity).navigation()
                }

                "16" -> {//找货啦

                }

                else -> {

                }

            }


        }

        fun aroutMessagePager(
            mContext: Context,
            jt: CustomMessageChatBean,
            mViewChatBg: View?
        ) {
            mViewChatBg?.setOnClickListener {
                val t = jt.t
                val ti = jt.ti
                val tt = jt.tt
                when (t) {
                    Constants.MESSAGE_TAG_1000 -> {//1000 货圈风险下线


                    }


                    else -> {

                    }

                }

            }


        }

        /**
         * @param tag
         */
        fun arout2page(
            mContext: Context,
            tag: String,
            id: String? = "",
            user: UserInfo? = null,
            type: String? = "",
            lordid: String? = "",
            adId: Int,//-1是不计入
            province: String? = ""
        ) {
            saveAdSttistics(adId)
            when (tag) {
                "0" -> {//0 商务合作
//                    ARouter.getInstance().build(ARoutUtils.CooperationActivity).navigation()
                }

                "1" -> {//1 app内 web
//                    WebActivity.openUrl(mContext, id)
                }

                "2" -> {//2 app外 web
                    val uriintent = Uri.parse(id)
                    val intent = Intent(Intent.ACTION_VIEW, uriintent)
                    mContext.startActivity(intent)
                }

                "3" -> {//3 商品
//                    ARouter.getInstance().build(ARoutUtils.GoodsDetilsActivity)
//                        .withString("spuid", id).navigation()
                }


            }

        }

        /**
         * 保存点击的广告id 根据日期合并
         * id为-1时不保存
         */
        fun saveAdSttistics(adId: Int) {
            if (adId == -1) {
                return
            }
//            showToast(adId)
            val json = SPStaticUtils.getString(Constants.AD_STATISTICS, "")
            val currentTime = TimeUtil.getNowDateTime("yyyy-MM-dd")
            LogUtils.e("广告AdSttistics===$json")
            if (json.isNullOrEmpty() || json == "") {
                val adList = mutableListOf<ADClickReqBody>()
                val adClickReqBody = ADClickReqBody(adId, 1, currentTime)
                adList.add(adClickReqBody)
                val listJosn = GsonUtils.toJson(adList)
                SPStaticUtils.put(Constants.AD_STATISTICS, listJosn)
//                showToast(listJosn)
            } else {
                val jsonType = object : TypeToken<List<ADClickReqBody>?>() {}.type
                val adClickReqBody: List<ADClickReqBody> = GsonUtils.fromJson(json, jsonType)
                var hits = 0
                for (item in adClickReqBody) {
                    val adid = item.adid
                    val dateTime = item.date
                    if (adid == adId && dateTime == currentTime) {
                        item.hits++
                        hits++
                        break
                    }
                }
                if (hits == 0) {
                    val adLists = mutableListOf<ADClickReqBody>()
                    adLists.addAll(adClickReqBody)
                    val adHitReqBody = ADClickReqBody(adId, 1, currentTime)
                    adLists.add(adHitReqBody)
                    val listJosn = GsonUtils.toJson(adLists)
                    SPStaticUtils.put(Constants.AD_STATISTICS, listJosn)
//                    showToast(listJosn)
                } else {
                    val listJosn = GsonUtils.toJson(adClickReqBody)
                    SPStaticUtils.put(Constants.AD_STATISTICS, listJosn)
//                    showToast(listJosn)
                }
            }

        }

        /**
         * 获取保存的广告
         */
        fun getAdSttistics(): List<ADClickReqBody> {
            val json = SPStaticUtils.getString(Constants.AD_STATISTICS, "")
            if (json.isNullOrEmpty() || json == "") {
                return mutableListOf<ADClickReqBody>()
            } else {
                val jsonType = object : TypeToken<List<ADClickReqBody>?>() {}.type
                val adClickReqBody: List<ADClickReqBody> = GsonUtils.fromJson(json, jsonType)
                return adClickReqBody
            }
        }

        /**
         * @param tag
         */
        fun arout2pageNoLogin(
            mContext: Context,
            tag: String,
            id: String? = "",
            adId: Int
        ) {
            saveAdSttistics(adId)
            when (tag) {


            }
        }


        fun startMain(mainTab: Int = 0, context: Context, tag: String, id: String, adId: Int) {
            ARouter.getInstance().build(ARoutUtils.HomeActivityURL)
                .withInt("TabId", mainTab)
                .navigation(
                    context,
                    object : NavigationCallback {
                        override fun onFound(postcard: Postcard?) {
                        }

                        override fun onLost(postcard: Postcard?) {
                        }

                        override fun onArrival(postcard: Postcard?) {
                            arout2page(context, tag, id, adId = adId)
                        }

                        override fun onInterrupt(postcard: Postcard?) {
                        }

                    })
//            object : SimpleNavigationCallback() {
//                override fun onArrival(postcard: Postcard) {
//                    if (!TextUtils.isEmpty(url)) {
//                        val _url = url!!.replace("\\/", "/")
//                        ARouter.getInstance()
//                            .build(ARoutUtils.HomeActivityURL)
//                            .withString("RouterConstants.Param.WEB_URL", _url)
//                            .navigation()
//                    }
//                }
//            })
        }


        fun checkLoginToTarget(
            user: UserInfo?,
            postcard: Postcard,
//            TAGACTIVIFY: String
            func: () -> Unit
        ) {//Postcard 是 Arouter 的类
            if (user != null && !user.id.isNullOrEmpty()) {
//                postcard.navigation()
                func()
            } else {
                //不能使用 postcard 切换 path 直接跳转，因为 group 可能不同，所以重新 build
                ARouter.getInstance().build(ARoutUtils.OneKeyLoginActivityURL)
                    .with(postcard.extras)//获取携带的参数重新转入
                    .withParcelable(ARoutUtils.AROUT_TAG, AroutBean(postcard.path))//添加目标路由
                    .navigation()
            }
        }

//        fun checkLoginToTarget(
//            postcard: Postcard,
//        ) {//Postcard 是 Arouter 的类
//            //不能使用 postcard 切换 path 直接跳转，因为 group 可能不同，所以重新 build
//            ARouter.getInstance().build(ARoutUtils.OneKeyLoginActivityURL)
//                .with(postcard.extras)//获取携带的参数重新转入
//                .withString(ARoutUtils.AROUT_TAG, postcard.path)//添加目标路由
//                .navigation()
//        }

        //检查登录后的路由分发
        fun LoginToTarget(aroutBean: AroutBean?, res: UserInfo) {
            val url = aroutBean?.url
            if (!url.isNullOrEmpty()) {
                when (url) {
//                    ARoutUtils.SearchGoodsActivity -> {
//                        ARouter.getInstance().build(url)
//                            .withString("name", res.name)
//                            .withString("phone", res.phone).navigation()
//                    }
//
//                    ARoutUtils.ApplyQuanUseActivity -> {
//                        if (!res.couponid.isNullOrEmpty()) {
//                            LiveEventBus.get(ClosePageEvent::class.java)
//                                .post(ClosePageEvent(ARoutUtils.ApplyQuanActivity))
//                            ARouter.getInstance().build(ARoutUtils.ApplyQuanUseActivity)
//                                .withString("couponId", res.couponid).navigation()
//                        } else {
////                            ARouter.getInstance().build(ARoutUtils.ApplyQuanActivity).navigation()
//                        }
//                    }
                }

            }
        }

        fun scanMediaPic(banner: String?, position: Int = 0) {
            if (banner.isNullOrEmpty()) {
                return
            }
            val mFacoryDatas = mutableListOf<ViewTypeStringBean>()
            mFacoryDatas.add(ViewTypeStringBean(banner, ViewTypeStringBean.PIC_TYPE))
            val json = GsonUtils.toJson(mFacoryDatas)
            ARouter.getInstance().build(ARoutUtils.ShowMediaDetailsActivity)
                .withInt("position", position)
                .withString("data", json)
                .navigation()
        }

        fun scanMediaVideo(banner: String?, position: Int = 0) {
            if (banner.isNullOrEmpty()) {
                return
            }
            val mFacoryDatas = mutableListOf<ViewTypeStringBean>()
            mFacoryDatas.add(ViewTypeStringBean(banner, ViewTypeStringBean.VEDIO_TYPE))
            val json = GsonUtils.toJson(mFacoryDatas)
            ARouter.getInstance().build(ARoutUtils.ShowMediaDetailsActivity)
                .withInt("position", position)
                .withString("data", json)
                .navigation()
        }


        fun scanMediaPic(banner: MutableList<String>, position: Int = 0) {
            if (banner.size == 0) {
                return
            }
            val mFacoryDatas = mutableListOf<ViewTypeStringBean>()
            for (i in 0 until banner.size) {
                val tvivItemBean = banner[i]
                mFacoryDatas.add(ViewTypeStringBean(tvivItemBean, ViewTypeStringBean.PIC_TYPE))
            }
            val json = GsonUtils.toJson(mFacoryDatas)
            ARouter.getInstance().build(ARoutUtils.ShowMediaDetailsActivity)
                .withInt("position", position)
                .withString("data", json)
                .navigation()
        }

        fun scanMediaPicLocal(banner: MutableList<LocalMedia?>, position: Int = 0) {
            if (banner.size == 0) {
                return
            }
            val mFacoryDatas = mutableListOf<ViewTypeStringBean>()
            for (i in 0 until banner.size) {
                val tvivItemBean = banner[i]?.compressPath ?: banner[i]?.realPath ?: ""
                mFacoryDatas.add(ViewTypeStringBean(tvivItemBean, ViewTypeStringBean.PIC_TYPE))
            }
            val json = GsonUtils.toJson(mFacoryDatas)
            ARouter.getInstance().build(ARoutUtils.ShowMediaDetailsActivity)
                .withInt("position", position)
                .withString("data", json)
                .navigation()
        }

        fun scanMediaPicType(mFacoryDatas: MutableList<ViewTypeStringBean>, position: Int = 0) {
            if (mFacoryDatas.size == 0) {
                return
            }
            val json = GsonUtils.toJson(mFacoryDatas)
            ARouter.getInstance().build(ARoutUtils.ShowMediaDetailsActivity)
                .withInt("position", position)
                .withString("data", json)
                .navigation()
        }

        fun scanMediaType(mFacoryDatas: MutableList<ViewTypeBean>, position: Int = 0) {
            if (mFacoryDatas.size == 0) {
                return
            }
            val list = mutableListOf<ViewTypeStringBean>()
            mFacoryDatas.forEach {
                list.add(
                    ViewTypeStringBean(
                        it.data.imageFirst ?: it.data.image ?: "", it.type
                    )
                )
            }
            val json = GsonUtils.toJson(list)
            ARouter.getInstance().build(ARoutUtils.ShowMediaDetailsActivity)
                .withInt("position", position)
                .withString("data", json)
                .navigation()
        }
    }
}